package com.example.apidocserver.application.event.impl;

import com.example.apidocserver.application.event.SysUserEvent;
import com.example.apidocserver.domain.system.entity.SysImages;
import com.example.apidocserver.domain.system.service.SysImagesService;
import com.example.apidocserver.domain.user.entity.DocUsrHis;
import com.example.apidocserver.domain.user.event.UserDocInfoEventService;
import com.example.apidocserver.infrastructure.config.security.UserDetailsImpl;
import com.example.apidocserver.infrastructure.enums.HisIdEnum;
import com.example.apidocserver.interfaces.vo.UserVo;
import lombok.extern.slf4j.Slf4j;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;

/**
 * 用户事件
 *
 * @author xyqlg
 */
@Service
@Slf4j
public class SysUserEventImpl implements SysUserEvent {
    @Resource
    private SysImagesService sysImagesService;

    @Resource
    private UserDocInfoEventService userDocInfoEventService;

    @Override
    public UserVo getCurrentUser() {
        // 获取当前用户认证信息
        Authentication authentication = SecurityContextHolder.getContext().getAuthentication();
        if (authentication != null && authentication.getPrincipal() instanceof UserDetailsImpl) {
            // 如果认证信息中有用户信息，返回当前用户信息
            UserDetailsImpl userDetails = (UserDetailsImpl) authentication.getPrincipal();

            UserVo userVo = new UserVo();
            userVo.setUserId(userDetails.getUserId()).setNickName(userVo.getNickName())
                    .setAvatarImgId(userDetails.getAvatarImgId());

            SysImages sysImages = sysImagesService.queryById(userVo.getAvatarImgId());
            userVo.setSysImages(sysImages);
            return userVo;
        } else {
            // 否则返回空值
            return null;
        }
    }

    @Override
    public void setUserHis(HisIdEnum hisIdEnum, Integer id) {
        DocUsrHis usrLastInfo = userDocInfoEventService.getUsrLastInfo();
        switch (hisIdEnum) {
            case SPACE:
                usrLastInfo.setSpaceId(id);
                userDocInfoEventService.setHisId(usrLastInfo, hisIdEnum);
                return;
            case DOC:
                usrLastInfo.setDocId(id);
                userDocInfoEventService.setHisId(usrLastInfo, hisIdEnum);
                return;
            case API:
                usrLastInfo.setApiId(id);
                userDocInfoEventService.setHisId(usrLastInfo, hisIdEnum);
                return;
            case ENV:
                usrLastInfo.setEnvId(id);
                userDocInfoEventService.setHisId(usrLastInfo, hisIdEnum);
                return;
            case HIS:
                usrLastInfo.setHisId(id);
                userDocInfoEventService.setHisId(usrLastInfo, hisIdEnum);
                return;
            default:
                log.error("入参枚举错误");
        }
    }
}
